package com.sum.tea.rongrui.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.StringUtils.getString
import com.example.lib_rongrui.RrReader
import com.example.lib_rongrui.Util
import com.sum.tea.R
import com.sum.tea.databinding.ActivityRw6cBinding
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

enum class CheckType {
    CHECK_W_6C,
    CHECK_R_6C
}

class ReadWriteViewModel : ViewModel() {

    private val _result = MutableLiveData<String>()
    val result: LiveData<String> = _result

    var selectedEd: Int = 3

    fun checkContent(checkType: CheckType, binding: ActivityRw6cBinding): Boolean {
        return when (checkType) {
            CheckType.CHECK_W_6C -> {
                when {
                    Util.isEtEmpty(binding.etContent6c) -> {
                        Util.showWarning(binding.root.context, R.string.content_empty_warning)
                        false
                    }
                    binding.etContent6c.text.toString().length % 4 != 0 -> {
                        Util.showWarning(binding.root.context, R.string.length_content_warning)
                        false
                    }
                    !Util.isLenLegal(binding.etContent6c) -> {
                        Util.showWarning(binding.root.context, R.string.str_lenght_odd_warning)
                        false
                    }
                    !Util.isLenLegal(binding.etPwd) -> {
                        Util.showWarning(binding.root.context, R.string.str_lenght_odd_warning)
                        false
                    }
                    else -> true
                }
            }
            CheckType.CHECK_R_6C -> {
                when {
                    Util.isEtEmpty(binding.etWordptr) -> {
                        Util.showWarning(binding.root.context, R.string.wordptr_empty_warning)
                        false
                    }
                    Util.isEtEmpty(binding.etLength) -> {
                        Util.showWarning(binding.root.context, R.string.length_empty_warning)
                        false
                    }
                    Util.isEtEmpty(binding.etPwd) -> {
                        Util.showWarning(binding.root.context, R.string.pwd_empty_warning)
                        false
                    }
                    !Util.isLenLegal(binding.etPwd) -> {
                        Util.showWarning(binding.root.context, R.string.str_lenght_odd_warning)
                        false
                    }
                    else -> true
                }
            }
        }
    }

    fun writeData(epc: String, mem: Byte, wordPtr: Byte, password: String, data: String) {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                val result = RrReader.rrlib.WriteData_G2(data, epc, mem, wordPtr.toInt(), password)
                withContext(Dispatchers.Main) {
                    if (result != 0) {
                        RrReader.writelog(getString(R.string.write_failed), null)
                        _result.value = getString(R.string.write_failed)
                    } else {
                        RrReader.writelog(getString(R.string.write_success), null)
                        _result.value = getString(R.string.write_success)
                    }
                }
            } catch (e: Exception) {
                withContext(Dispatchers.Main) {
                    RrReader.writelog(getString(R.string.write_failed), null)
                    _result.value = getString(R.string.write_failed)
                }
            }
        }
    }

    fun readData(epc: String, mem: Byte, wordPtr: Int, num: Int, password: String) {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                val strData = RrReader.rrlib.ReadData_G2(epc, mem, wordPtr, num.toByte(), password)
                withContext(Dispatchers.Main) {
                    if (strData == null) {
                        RrReader.writelog(getString(R.string.get_failed), null)
                        _result.value = getString(R.string.get_failed)
                    } else {
                        RrReader.writelog(getString(R.string.get_success), null)
                        _result.value = getString(R.string.get_success)
                    }
                }
            } catch (e: Exception) {
                withContext(Dispatchers.Main) {
                    RrReader.writelog(getString(R.string.get_failed), null)
                    _result.value = getString(R.string.get_failed)
                }
            }
        }
    }

    fun writeEPC(password: String, data: String) {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                val result = RrReader.rrlib.WriteEPC_G2(data, password)
                withContext(Dispatchers.Main) {
                    if (result != 0) {
                        RrReader.writelog(getString(R.string.write_failed), null)
                        _result.value = getString(R.string.write_failed)
                    } else {
                        RrReader.writelog(getString(R.string.write_success), null)
                        _result.value = getString(R.string.write_success)
                    }
                }
            } catch (e: Exception) {
                withContext(Dispatchers.Main) {
                    RrReader.writelog(getString(R.string.write_failed), null)
                    _result.value = getString(R.string.write_failed)
                }
            }
        }
    }

    fun killTag(password: String, epc: String, isU9Lock: Boolean, lockMem: Byte, lockType: Byte) {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                if (password.length != 8) {
                    withContext(Dispatchers.Main) {
                        RrReader.writelog(getString(R.string.kill_failed), null)
                        _result.value = getString(R.string.kill_failed)
                    }
                    return@launch
                }
                val killWord = Util.hexStringToBytes(password)
                val epcNum = (epc.length / 4).toByte()
                val errorCode = ByteArray(1)
                val result = RrReader.rrlib.Kill_G2(epcNum, null, killWord, errorCode)
                withContext(Dispatchers.Main) {
                    if (result != 0) {
                        RrReader.writelog(getString(R.string.kill_failed), null)
                        _result.value = getString(R.string.kill_failed)
                    } else {
                        RrReader.writelog(getString(R.string.kill_success), null)
                        _result.value = getString(R.string.kill_success)
                    }
                }
            } catch (e: Exception) {
                withContext(Dispatchers.Main) {
                    RrReader.writelog(getString(R.string.kill_failed), null)
                    _result.value = getString(R.string.kill_failed)
                }
            }
        }
    }

    fun lockTag(password: String, epc: String, lockMem: Byte, lockType: Byte, isU9Lock: Boolean) {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                val select = if (isU9Lock) 255.toByte() else lockMem
                val setProtect = if (isU9Lock) 255.toByte() else lockType
                val passwordBytes = Util.hexStringToBytes(password)
                val epcNum = (epc.length / 4).toByte()
                val errorCode = ByteArray(1)
                val result = RrReader.rrlib.Lock_G2(epcNum, null, select, setProtect, passwordBytes, errorCode)
                withContext(Dispatchers.Main) {
                    if (result != 0) {
                        RrReader.writelog(getString(R.string.lock_failed), null)
                        _result.value = getString(R.string.lock_failed)
                    } else {
                        RrReader.writelog(getString(R.string.lock_success), null)
                        _result.value = getString(R.string.lock_success)
                    }
                }
            } catch (e: Exception) {
                withContext(Dispatchers.Main) {
                    RrReader.writelog(getString(R.string.lock_failed), null)
                    _result.value = getString(R.string.lock_failed)
                }
            }
        }
    }

    fun toggleLED(password: String, epc: String) {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                var result = 0x30
                for (index in 0 until 5) {
                    result = RrReader.rrlib.LedOn_kx2005x(epc, password, 7.toByte())
                    if (result == 0) break
                }
                withContext(Dispatchers.Main) {
                    if (result != 0) {
                        RrReader.writelog(getString(R.string.Optfailed), null)
                        _result.value = getString(R.string.Optfailed)
                    } else {
                        RrReader.writelog(getString(R.string.Optsuccess), null)
                        _result.value = getString(R.string.Optsuccess)
                    }
                }
            } catch (e: Exception) {
                withContext(Dispatchers.Main) {
                    RrReader.writelog(getString(R.string.Optfailed), null)
                    _result.value = getString(R.string.Optfailed)
                }
            }
        }
    }

    fun readTemperature(password: String, epc: String) {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                var tempResult = ""
                for (index in 0 until 3) {
                    tempResult = RrReader.rrlib.SCR409_GetTemperature(epc, password)
                    if (!tempResult.isNullOrEmpty()) break
                }
                withContext(Dispatchers.Main) {
                    if (tempResult.isNullOrEmpty()) {
                        RrReader.writelog(getString(R.string.Optfailed), null)
                        _result.value = getString(R.string.Optfailed)
                    } else {
                        RrReader.writelog(getString(R.string.Optsuccess), null)
                        _result.value = getString(R.string.Optsuccess)
                        // 假设有一个 LiveData 或其他方式更新温度显示
                    }
                }
            } catch (e: Exception) {
                withContext(Dispatchers.Main) {
                    RrReader.writelog(getString(R.string.Optfailed), null)
                    _result.value = getString(R.string.Optfailed)
                }
            }
        }
    }
}
